﻿/*
 * 由SharpDevelop创建。
 * 用户： Administrator
 * 日期: 2025/2/27
 * 时间: 2:51
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace pdfpb
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		public MainForm()
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			
//			AddBlankPagesToMultipleOf4("1.pdf","temp.pdf");
//			CreateBooklet("temp.pdf","2.pdf");                补全空白页，生成小册子
			
//			SplitBy20Pages("1.pdf","split");
//			ProcessDirectory("split");
//			MergeFolderPdfs("booklet","合并.pdf");      

		//	RemoveLastPageLegacy("3.pdf","4.pdf");
			//
			// TODO: Add constructor code after the InitializeComponent() call.
			//
		}
		
		//删除最后一页
		public void RemoveLastPageLegacy(string inputPath, string outputPath)
		{
		    PdfReader reader = new PdfReader(inputPath);
		    int totalPages = reader.NumberOfPages;
		    
		    using (Document doc = new Document())
		    {
		        PdfCopy copy = new PdfCopy(doc, new FileStream(outputPath, FileMode.Create));
		        doc.Open();
		        
		        // 复制除最后一页外的所有页面
		        for (int i = 1; i < totalPages; i++)
		        {
		            PdfImportedPage page = copy.GetImportedPage(reader, i);
		            copy.AddPage(page);
		        }
		        doc.Close();
		    }
		    reader.Close();
		}
		
		 //***************************
		 private static void ProcessDirectory(string targetDirectory)
	    {
		 	if (!Directory.Exists("booklet")) {
		 		Directory.CreateDirectory("booklet");
		 	}
	        // 处理当前目录文件 (示例: 仅处理PDF文件)
	        string[] fileEntries = Directory.GetFiles(targetDirectory, "*.pdf");
	        foreach (string filePath in fileEntries)
	        {
	        	//CreateBooklet(filePath,"booklet\\B"+filePath.Replace("split\\S",""));
	        	
	        	if (isblankPagesNeeded(filePath)) {
					AddBlankPagesToMultipleOf4(filePath,"temp.pdf");
					CreateBooklet("temp.pdf","booklet\\B"+filePath.Replace("split\\S",""));              //  补全空白页，生成小册子
					File.Delete("temp.pdf");
				}else{
					CreateBooklet(filePath,"booklet\\B"+filePath.Replace("split\\S",""));  
				}
	        }
	 
	    }

 
		 //*******************************合并PDF
		 /// <summary>
    /// 合并文件夹中所有PDF文件（保留原页面尺寸和旋转）
    /// </summary>
    /// <param name="folderPath">源文件夹路径</param>
    /// <param name="outputPath">输出文件路径</param>
    public static void MergeFolderPdfs(string folderPath, string outputPath)
    {
        // 获取文件夹中所有PDF文件并按名称排序
        List<string> pdfFiles = GetSortedPdfFiles(folderPath);
        
        using (Document doc = new Document())
        {
            // 使用PdfSmartCopy优化内存
            PdfCopy copy = new PdfSmartCopy(doc, new FileStream(outputPath, FileMode.Create));
            doc.Open();

            foreach (string file in pdfFiles)
            {
                using (PdfReader reader = new PdfReader(file))
                {
                     
                    for (int i = 1; i <= reader.NumberOfPages; i++)
                    {
                        PdfImportedPage page = copy.GetImportedPage(reader, i);
                        copy.AddPage(page);
                    }
                    copy.FreeReader(reader); // 释放资源
                }
            }
            doc.Close();
        }
    }

    // 获取排序后的PDF文件列表（按文件名升序）
    private static List<string> GetSortedPdfFiles(string folderPath)
    {
        var files = Directory.GetFiles(folderPath, "*.pdf")
                     .OrderBy(f => f)
                     .ToList();
        if (files.Count == 0)
            throw new FileNotFoundException("文件夹中未找到PDF文件");
        return files;
    }
		 
		 //********************************
		
		/// <summary>
		/// 创建fold 2x1 duplex拼版，正反打印小册子
		/// </summary>
		/// <param name="inputPath"></param>
		/// <param name="outputPath"></param>
		public static void CreateBooklet(string inputPath, string outputPath)
		{
		    // 读取原始PDF文件（支持多页）
		    PdfReader reader = new PdfReader(inputPath);
		    int totalPages = reader.NumberOfPages;
		
		    // 创建A4横向文档（容纳两个并排页面）
		    Document doc = new Document(PageSize.A4.Rotate()); // 842pt宽 × 595pt高
		    PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(outputPath, FileMode.Create));
		    doc.Open();
		    PdfContentByte cb = writer.DirectContent;
		    
//		    int pages=0;
//		    
//		    if (totalPages%2==0) {
//		    	pages=totalPages/2;
//		    }else{
//		    	pages=totalPages/2+1;
//		    }
		
		    // 遍历所有页面，按小册子顺序排列（如总页数4时的布局：4|1和2|3）
		    for (int i = 0; i < totalPages/2; i ++)
		    {
		        doc.NewPage();
		        
		        if (i%2==0) {
		        	// 左侧页面：从后往前取（如第4页）
			        int leftPage = totalPages - i;
			        if (leftPage > 0)
			        {
			            PdfImportedPage pageLeft = writer.GetImportedPage(reader, leftPage);
			            iTextSharp.text.Rectangle sizeLeft = reader.GetPageSizeWithRotation(leftPage);
			            float scaleX = (PageSize.A4.Width *0.7f) / sizeLeft.Width; // 缩放到A4宽度的50%
			            cb.AddTemplate(pageLeft, scaleX, 0, 0, scaleX, 0, 0);    // 左下角定位
			        }
			
			        // 右侧页面：从前往后取（如第1页）
			        int rightPage = i + 1;
			        if (rightPage <= totalPages)
			        {
			            PdfImportedPage pageRight = writer.GetImportedPage(reader, rightPage);
			            iTextSharp.text.Rectangle sizeRight = reader.GetPageSizeWithRotation(rightPage);
			            float scaleY = (PageSize.A4.Width *0.7f) / sizeRight.Width;
			            cb.AddTemplate(pageRight, scaleY, 0, 0, scaleY, PageSize.A4.Width *0.7f, 0); // 右侧定位
			        }
		        }else{
		        	// 左侧页面：从后往前取（如第4页）
			        int leftPage = i + 1;
			        if (leftPage > 0)
			        {
			            PdfImportedPage pageLeft = writer.GetImportedPage(reader, leftPage);
			            iTextSharp.text.Rectangle sizeLeft = reader.GetPageSizeWithRotation(leftPage);
			            float scaleX = (PageSize.A4.Width *0.7f) / sizeLeft.Width; // 缩放到A4宽度的50%
			            cb.AddTemplate(pageLeft, scaleX, 0, 0, scaleX, 0, 0);    // 左下角定位
			        }
			
			        // 右侧页面：从前往后取（如第1页）
			        int rightPage = totalPages - i;
			        if (rightPage <= totalPages)
			        {
			            PdfImportedPage pageRight = writer.GetImportedPage(reader, rightPage);
			            iTextSharp.text.Rectangle sizeRight = reader.GetPageSizeWithRotation(rightPage);
			            float scaleY = (PageSize.A4.Width *0.7f) / sizeRight.Width;
			            cb.AddTemplate(pageRight, scaleY, 0, 0, scaleY, PageSize.A4.Width *0.7f, 0); // 右侧定位
			        }
		        }
		        
		        
		    }
		
		    doc.Close();
		    reader.Close();
		}
		
		
		public static bool isblankPagesNeeded(string inputPath){
			PdfReader reader = new PdfReader(inputPath);
		    int totalPages = reader.NumberOfPages;
		    int remainder = totalPages % 4;
		    int blankPagesNeeded = (remainder == 0) ? 0 : 4 - remainder;
		    if (blankPagesNeeded > 0){
		    	return true;
		    }else{
		    	return false;
		    }
		}
		/// <summary>
		/// 给pdf添加空白页至4的倍数
		/// </summary>
		/// <param name="inputPath"></param>
		/// <param name="outputPath"></param>
		public static void AddBlankPagesToMultipleOf4(string inputPath, string outputPath)
		{
		    PdfReader reader = new PdfReader(inputPath);
		    int totalPages = reader.NumberOfPages;
		    int remainder = totalPages % 4;
		    int blankPagesNeeded = (remainder == 0) ? 0 : 4 - remainder;
		
		    // 若需补页则执行添加操作
		    if (blankPagesNeeded > 0)
		    {
		        // 使用PdfStamper高效插入空白页（推荐方案）
		        using (PdfStamper stamper = new PdfStamper(reader, new FileStream(outputPath, FileMode.Create)))
		        {
		            // 获取最后一页尺寸（含旋转信息）
		            iTextSharp.text.Rectangle lastPageSize = reader.GetPageSizeWithRotation(totalPages);
		            
		            // 从后往前插入空白页（避免索引偏移问题）
		            for (int i = 0; i < blankPagesNeeded; i++)
		            {
		                stamper.InsertPage(totalPages + 1, lastPageSize); // 继承最后一页的尺寸
		                totalPages++;
		            }
		        }
		    }
		    reader.Close();
		}
		
		//*****************************************切割PDF*****************************
		 
		public void SplitBy20Pages(string inputPath, string outputFolder)
	    {
			if (!Directory.Exists(outputFolder)) {
		 		Directory.CreateDirectory(outputFolder);
		 	}
	        PdfReader reader = new PdfReader(inputPath);
	        int totalPages = reader.NumberOfPages;
	
	        // 计算分块数量并处理不足20页的情况 
	        int chunks = (totalPages + 19) / 20; 
	
	        for (int chunk = 0; chunk < chunks; chunk++)
	        {
	            int start = chunk * 20 + 1;
	            int end = Math.Min((chunk + 1) * 20, totalPages);
	            string outputPath = Path.Combine(outputFolder, "S"+(chunk + 1)+".pdf");
	            CreateChunkFile(reader, outputPath, start, end);
	        }
	        reader.Close();
	    }
	
	    private void CreateChunkFile(PdfReader reader, string outputPath, int startPage, int endPage)
	    {
	        using (Document doc = new Document())
	        {
	            // 使用PdfSmartCopy优化内存 
	            PdfCopy copy = new PdfSmartCopy(doc, new FileStream(outputPath, FileMode.Create));
	            doc.Open();
	
	            for (int pageNum = startPage; pageNum <= endPage; pageNum++)
	            {
	                // 获取页面尺寸及旋转参数 
	                iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(pageNum);
	                int rotation = reader.GetPageRotation(pageNum);
	                PdfImportedPage page = copy.GetImportedPage(reader, pageNum);
	
	                // 处理旋转页面 
	                if (rotation == 90 || rotation == 270)
	                {
	                    AddRotatedPage(copy, page, rotation, size);
	                }
	                else
	                {
	                    copy.AddPage(page); // 直接添加非旋转页面
	                }
	            }
	            doc.Close();
	        }
	    }
	
	    private void AddRotatedPage(PdfCopy copy, PdfImportedPage page, int rotation, iTextSharp.text.Rectangle size)
	    {
	        PdfContentByte cb = copy.DirectContent;
	        switch (rotation)
	        {
	            case 90:
	                cb.AddTemplate(page, 0, -1f, 1f, 0, 0, size.Height);
	                break;
	            case 270:
	                cb.AddTemplate(page, 0, 1f, -1f, 0, size.Width, 0);
	                break;
	        }
	    }
	    string path1="";
	    string path2="";
		void TextBox1DragDrop(object sender, DragEventArgs e)
		{
			textBox1.Text=((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
			path1=textBox1.Text;
		}
		void TextBox1DragEnter(object sender, DragEventArgs e)
		{
			if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Link;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
		}
		void Button1Click(object sender, EventArgs e)
		{
			if (isblankPagesNeeded(path1)) {
				AddBlankPagesToMultipleOf4(path1,"temp.pdf");
				CreateBooklet("temp.pdf","小册子.pdf");              //  补全空白页，生成小册子
				File.Delete("temp.pdf");
			}else{
				CreateBooklet(path1,"小册子.pdf");  
			}
			
		}
		void TextBox2DragDrop(object sender, DragEventArgs e)
		{
			textBox2.Text=((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
			path2=textBox2.Text;
		}
		void TextBox2DragEnter(object sender, DragEventArgs e)
		{
			if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Link;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
		}
		void Button2Click(object sender, EventArgs e)
		{
			SplitBy20Pages(path2,"split");
			ProcessDirectory("split");
			MergeFolderPdfs("booklet","隔页小册子.pdf");
		}
		//**************************************
	}
}
